##############################################################################
# Copyright (c) 2016-20, Lawrence Livermore National Security, LLC and Umpire
# project contributors. See the COPYRIGHT file for details.
#
# SPDX-License-Identifier: (MIT)
##############################################################################
from __future__ import print_function

ops = [
    "copy",
]

sources = [ "HOST" ]
dests = ["HOST"]

def gen_allocate_test_subroutines():
    print('')

    print("""
module umpire_fortran_op_tests

  use iso_c_binding
  use fruit
  use umpire_mod
  implicit none

  contains
""")

    print('')

    for op in ops:
        for source in sources:
            for dest in dests:
                print("""
      subroutine test_{op}_{src}_{dst}
        use iso_c_binding

        type(UmpireResourceManager) rm
        type(UmpireAllocator) source_allocator
        type(UmpireAllocator) dest_allocator

        type(C_PTR) source
        type(C_PTR) dest

        rm = rm%get_instance()
        source_allocator = rm%get_allocator_by_name("{source}")
        dest_allocator = rm%get_allocator_by_name("{dest}")

        source = source_allocator%allocate_pointer(1024_8)
        dest = dest_allocator%allocate_pointer(1024_8)

        call rm%{op}(dest, source)

        call assert_true(.true.)

        call source_allocator%deallocate_pointer(source)
        call dest_allocator%deallocate_pointer(dest)

        call source_allocator%delete()
        call dest_allocator%delete()
      end subroutine test_{op}_{source}_{dest}

    """.format(
            op=op,
            src=source.lower(), 
            dst=dest.lower(),
            source=source,
            dest=dest
        ))

    print("""
end module umpire_fortran_op_tests
""")


def gen_allocate_test_calls():
    for op in ops:
        for source in sources:
            for dest in dests:
                print('  call test_{op}_{src}_{dst}'.format(op=op, src=source.lower(), dst=dest.lower()))


def gen_fortran():
    print('! Generated by genumpireftests.py')
    print('')

    gen_allocate_test_subroutines()

    print("""
program fortran_test
  use fruit
  use umpire_fortran_op_tests

  implicit none
  logical ok

  call init_fruit
""")

    gen_allocate_test_calls()

    print("""
  call fruit_summary
  call fruit_finalize

  call is_all_successful(ok)
  if (.not. ok) then
    call exit(1)
  endif
end program fortran_test
""")

if __name__ == '__main__':
    gen_fortran()
